package com.ruoyi.aitcommon.config;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.LogUtils;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.util.ScheduleUtils;

import cn.hutool.core.util.StrUtil;

/**
 * 任务配置管理类
 * 启动时会加载所有任务
 */
@Component
//sysJobServiceImpl 启动会清除所有任务
@DependsOn({"configManager","sysJobServiceImpl"})
public class TaskConfig {
	@Autowired
	private Scheduler scheduler;
	@Autowired
	private ConfigManager configManager;
	@Value("${ait.taskpath}")
	private String taskPath;

//	所有的任务清单
	private List<SysJob> joblist = new ArrayList<SysJob>();

	@PostConstruct
	void init() throws Exception {
		this.loadConfig();
	}

	/**
	 * 获取配置文件中 ait.taskpath 中的所有任务
	 * @return JOB LIST
	 * @throws Exception
	 */
	public List<SysJob> getJobListByParm() throws Exception {
		List<SysJob> retlist=new ArrayList<>();
		List<String> split = StrUtil.split(taskPath, ',');
		
		for(String parm:split) {
			if(configManager.hasContextByParm(parm)){
				Object json = configManager.getContextByParm(parm);
				LogUtils.debug("TaskConfig json:"+json);
				if (json != null) {
					retlist.addAll(((JSONArray)json).toJavaList(SysJob.class));
				}
			}
		}
		
		return retlist;
	}
	/**
	 * 创建调度任务
	 * @param clear 是否清除之前的任务
	 * @throws Exception
	 */
	private void createTask(boolean clear) throws Exception {
//		构造定时任务
//		在sysJobServiceImpl中也清除了task，这里不用清除
		if(clear) {
			scheduler.clear();	
		}
		if(joblist==null||joblist.size()==0)
			return;
		for (SysJob job : joblist) {
			ScheduleUtils.createScheduleJob(scheduler, job);
			String msg="TaskConfig启动任务,ID:[%s],Name:[%s],status:[%s]";
			msg=String.format(msg, job.getJobId(),job.getJobName(),job.getStatus());
			LogUtils.debug(msg);
		}
	}
	
	private void loadConfig() throws Exception {
		LogUtils.info("TaskConfig Path:"+taskPath);
		if(StrUtil.isBlank(taskPath)) {
			LogUtils.warn("配置文件application-ait.yml中ait.taskpath为空");
			return;	
		}
		
//		加载任务配置
		this.joblist=this.getJobListByParm();
//		创建任务
		this.createTask(true);
	}
	
	/**
	 * 系统启动后,重新加载任务
	 * @throws Exception 
	 */
	public void reloadConfig() throws Exception {
//		重新加载源文件
		List<String> split = StrUtil.split(taskPath, ',');
		for(String parm:split) {
			configManager.reloadConfigByParm(parm);
		}
//		重新加载任务列表
		this.joblist=this.getJobListByParm();
//		创建调度任务
		this.createTask(true);
	}
	
	public SysJob getJob(Long taskid) {
		if(this.joblist==null)
			return null;
		for(SysJob job:this.joblist) {
			if(job.getJobId().equals(taskid))
				return job;
		}
		return null;
	}
}
